using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Globalization;

namespace TST.SharePoint.Shared
{
    public class WSSFieldDateTime : FieldDateTime, IDataFormatting
    {
        private SPFieldDateTime _field;

        /// <summary>
        /// Constructor.
        /// </summary>
        public WSSFieldDateTime()
        {
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="ID">The ID for the field.</param>
        public WSSFieldDateTime(string Id)
            : base(Id)
        {
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        public WSSFieldDateTime(SPFieldDateTime field)
        {
            this.Id = field.Id.ToString();
            _field = field;
        }

        public override string GetTypedValueAsString(object value)
        {
            if (value == null || _field == null)
                return null;
            return ((DateTime)value).ToString(SPContext.Current.Web.Locale);
        }

        public override string GetTypedValueFormatted(object value)
        {

            if (value == null || _field == null)
                return null;
            IDataFormatting formatting = this as IDataFormatting;
            if (formatting != null)
            {
                string format = formatting.DataFormatString;
                if (format.IndexOf(":") > 0)
                {
                    format = formatting.DataFormatString.Substring(format.IndexOf(":") + 1);
                    format = format.Replace("}", string.Empty);
                }
                return ((DateTime)value).ToString(format, SPContext.Current.Web.Locale);
            }
            return ((DateTime)value).ToString(SPContext.Current.Web.Locale);
        }

        #region IDataFormatting Members

        string IDataFormatting.DataFormatString
        {
            get {
                if (_field == null)
                    return string.Empty;

                if (_field.DisplayFormat == SPDateTimeFieldFormatType.DateTime)
                    return "{0:g}";
                else
                    return "{0:d}";
            }
        }

        #endregion
    }
}
